//
//  NetwoekTools.swift
//  Weibo T
//
//  Created by mac on 15/12/4.
//  Copyright © 2015年 陈肖坤. All rights reserved.
//

import UIKit
import AFNetworking

//OC中只能够枚举基本数据类型
//swift中 能够枚举任意类型
enum HTTPMethod: String {
    case POST = "POST"
    case GET = "GET"
}

private let hostName = "https://api.weibo.com/"
private let dataErrorDomain = "com.baidu.data.error"
//private let hostName = "https://test.weibo.com/"



//网络请求工具单例类
class NetworkTools: AFHTTPSessionManager {
    
    static let sharedTools: NetworkTools = {
        let url = NSURL(string: hostName)!
        let tools = NetworkTools(baseURL: url)
        //添加支持的反序列化格式
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return tools
    }()
    
    
    func requestJSONDict(method: HTTPMethod, urlString: String,parameters:[String : AnyObject]?,finished: (result:[String : AnyObject]?,error: NSError?) -> ()) {
        if method == HTTPMethod.GET {
            //实现GET请求
            GET(urlString, parameters: parameters, success: { (_, result) -> Void in
                if let dict = result as? [String : AnyObject] {
                    //执行成功回调
                    finished(result: dict, error: nil)
                    return
                }
                
                //如果程序走到这里  成功回调的结果 无法转换为字典形式的数据
                let error = NSError(domain: dataErrorDomain, code: -10000, userInfo: [NSLocalizedDescriptionKey : "数据格式错误"])
                finished(result: nil, error: error)
                }, failure: { (_, error) -> Void in
                    //执行失败的回调
                    print(error)
                    finished(result: nil, error: error)
            })
        } else {
            //实现POST请求
            POST(urlString, parameters: parameters, success: { (_, result) -> Void in
                if let dict = result as? [String : AnyObject] {
                    //执行成功回调
                    finished(result: dict, error: nil)
                    return
                }
                
                //如果程序走到这里  成功回调的结果 无法转换为字典形式的数据
                let error = NSError(domain: dataErrorDomain, code: -10000, userInfo: [NSLocalizedDescriptionKey : "数据格式错误"])
                finished(result: nil, error: error)
                }, failure: { (_, error) -> Void in
                    //执行失败的回调
                    print(error)
                    finished(result: nil, error: error)
            })
            
        }
    }
}
